export type LogType = 'warn' | 'info' | 'error' | 'log';

export function getConfig(): ApiConfig | undefined {
  const fs = require('fs');
  const path = require('path');
  const cmdPath = process.env.INIT_CWD || process.cwd();
  const apiConfigPath = cmdPath + path.sep + 'api.config.js';
  if (fs.existsSync(apiConfigPath)) {
    const configModulePath = path.relative(__dirname, apiConfigPath);
    const config: ApiConfig = require(configModulePath);
    if (config && config.configs && config.configs.length) {
      if (config.typeParameterReflects && config.typeParameterReflects.length) {
        config.configs.forEach(c => {
          if (c.markRequiredModelProperty === undefined) {
            c.markRequiredModelProperty = config.markRequiredModelProperty ?? false
          }
          if (c.typeParameterReflects) {
            c.typeParameterReflects = [...c.typeParameterReflects, ...config.typeParameterReflects]
          } else {
            c.typeParameterReflects = config.typeParameterReflects;
          }
        })
      }
      return config;
    } else {
      console.error('配置不能为空');
    }
  } else {
    console.error('缺少api.config.js');
  }
}

export const config = getConfig();

export interface ApiConfig {
  apiRoot: string;

  markRequiredModelProperty?: boolean;
  // 类型定义
  configs: ModuleConfig[];
  log: Array<LogType>;
  templates: { [key: string]: string };
  typeRoot: string;
  typeParameterReflects?: Array<{
    name: string;
    typeProperties: string[];
  }>;
  /**
   * 映射为any的类型
   */
  typesAsAny?: string[]
  typesAsVoid?: string[]
  unwrapTypes?: string[];
}

export interface ModuleConfig {
  /**
   * 是否严格区分Model属性的可选状态
   */
  markRequiredModelProperty?: boolean;
  templates?: { [key: string]: string };
  trimPaths?: string[];
  apiRoot?: string;
  typeRoot?: string;
  name?: string;
  log?: Array<LogType>;
  excludes?: RegExp[];
  includes?: RegExp[];
  typeParameterReflects?: Array<{
    name: string;
    typeProperties: string[];
  }>;
  url?: string;
}
